package com.jing.yao.modules.dict.service.impl;

import com.jing.yao.cache.CacheHelper;
import com.jing.yao.cache.RedisKeyEnum;
import com.jing.yao.code.UserCode;
import com.jing.yao.component.constants.BaseOperationEnum;
import com.jing.yao.component.mapper.YaoBaseMapper;
import com.jing.yao.exception.BusinessExceptionBuilder;
import com.jing.yao.modules.dict.dao.DictMapper;
import com.jing.yao.modules.dict.dao.entity.DictEntity;
import com.jing.yao.modules.dict.item.dao.DictItemMapper;
import com.jing.yao.modules.dict.item.dao.entity.DictItemEntity;
import com.jing.yao.modules.dict.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据字典类型信息表
 *
 * @author lr
 * @since 2019-05-31 10:50
 */
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private CacheHelper cacheHelper;

    @Autowired
    private DictItemMapper dictItemMapper;

    @Override
    public YaoBaseMapper<DictEntity> getMapper() {
        return dictMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processBeforeOperation(DictEntity entity, BaseOperationEnum operationEnum) {
        switch (operationEnum) {
            case INSERT:
                LambdaQueryWrapper<DictEntity> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(DictEntity::getDictCode, entity.getDictCode());
                DictEntity dictEntity = dictMapper.selectOne(wrapper);
                if (dictEntity != null) {
                    throw BusinessExceptionBuilder.build(UserCode.DICT_EXIST);
                }
                break;
            case DELETE:
                //删除缓存
                cacheHelper.delete(RedisKeyEnum.DICT_PREFIX.getKey() + entity.getDictCode());
                //删除数据字典项
                dictItemMapper.delete(Wrappers.<DictItemEntity>lambdaQuery().eq(DictItemEntity::getDictCode, entity.getDictCode()));
                break;
        }
    }
}
